package cookie;

import utils.CookieUtils;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * cookie练习
 * 完成登录功能，并使下次登录时的用户名有个默认值：上次提交的用户名
 */
public class C7_CookieLogin extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("C7_CookieLogin 被调用...");

        String username = "";
        String htmlMes = "";
        //获取cookie
        Cookie[] cookies = req.getCookies();
        Cookie cookie = CookieUtils.readCookieByName("username", cookies);
        if (null != cookie) {
            username = cookie.getValue();
            htmlMes = "value=\"" + username + "\"";
        }
        System.out.println(username);
        //返回登录页面
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        writer.print("<form action=\"" + req.getContextPath() + "/loginOkServlet\">" +
                "<h1>用户登录界面</h1>" +
                "用户名:<input type=\"text\" name=\"username\" " + htmlMes + "\"><br/>" +
                "密码:<input type=\"text\" name=\"password\"><br/>" +
                "<input type=\"submit\" value=\"登录\">" +
                "</form>");
        writer.flush();
        writer.close();
    }
}
